package mall.dao.impl;

import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import mall.bean.User;
import mall.dao.UserDao;
import mall.dao.handler.column.UNDERLINE;

public class UserDaoImpl implements UserDao {

	@Override
	public long count()  {
		String sql = "SELECT COUNT(uid) FROM user";
		return JdbcTemplate.query(new ScalarHandler<Long>(), sql);
	}
	
	@Override
	public void save(User obj)  {
		String sql = "INSERT INTO user ( user_name, password, email, phone ) VALUES (?, ?, ?, ?)";
		JdbcTemplate.update(sql, obj.getUserName(), obj.getPassword(), obj.getEmail(), obj.getPhone());
	}

	@Override
	public void delete(Long id)  {
		String sql = "DELETE FROM user WHERE uid = ?";
		JdbcTemplate.update(sql, id);
	}

	@Override
	public void update(User obj)  {
		String sql = "UPDATE user SET user_name = ?, password = ?, email = ?, phone = ? WHERE uid = ?";
		JdbcTemplate.update(sql, obj.getUserName(), obj.getPassword(), obj.getEmail(), obj.getPhone(), obj.getUid());
	}

	@Override
	public User findById(Long id)  {
		String sql = "SELECT uid, user_name, password, email, phone FROM user WHERE uid = ?";
		BeanHandler<User> h = new BeanHandler<User>(User.class, UNDERLINE.PROCESSOR);
		return JdbcTemplate.query(h, sql, id);
	}
	
	@Override
	public User findByName(String userName)  {
		String sql = "SELECT uid, user_name as userName, password, email, phone FROM user WHERE user_name = ?";
		return JdbcTemplate.query(new BeanHandler<User>(User.class), sql, userName);
	}

}
